package repository.relsys.services;

import java.io.BufferedInputStream;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.Collection;
import java.util.Iterator;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;

import repository.relsys.domainmodel.ltool.interfaces.LearningTool;
import repository.relsys.domainmodel.ltool.pojos.LearningToolCls;
import thewebsemantic.Bean2RDF;
import thewebsemantic.RDF2Bean;

public class RelsysExportImport {

	public static void export(LearningTool lt, String fileName, String syntax) {
		try {
			Model m = ModelFactory.createDefaultModel();
			m.setNsPrefix("lt",
					"http://diplomski.nelakolundzija.org/LTontology.rdf#");
			m.setNsPrefix("swc","http://data.semanticweb.org/ns/swc/ontology#");
			m.setNsPrefix("jenabean", "http://thewebsemantic.com/");
			m.setNsPrefix("dc", "http://purl.org/dc/elements/1.1/");
			m.setNsPrefix("xsd", "http://www.w3.org/2001/XMLSchema#");
			m.setNsPrefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");

			Bean2RDF writer = new Bean2RDF(m);

			writer.saveDeep(lt);
			m.write(new FileOutputStream(fileName), syntax);
			m.write(System.out, "RDF/XML");
		} catch (Exception e) {
			System.err.println("Error!");
			e.printStackTrace();
		}
	}

	public static LearningToolCls importLT(String fileName, String syntax) {

		LearningToolCls ltool = null;

		try {

			InputStream is = new BufferedInputStream(new FileInputStream(
					fileName));
			Model m = ModelFactory.createDefaultModel().read(
					new InputStreamReader(is),
					"http://diplomski.nelakolundzija.org/LTontology.rdf#",
					syntax);
			is.close();

			RDF2Bean reader = new RDF2Bean(m);

			Collection<LearningToolCls> ltools = reader
					.loadDeep(LearningToolCls.class);
			Iterator<LearningToolCls> iter = ltools.iterator();
			ltool = iter.next();

		} catch (Exception e) {
			System.err.println("Error in reading");
			e.printStackTrace();
		}

		return ltool;
	}

}
